﻿#include "pch.h"
#include "Block.h"

/**
 * 构造方法。
 */
Block::Block():
    mColor(0), 
    mDrawer(NULL), 
    mGameBoard(NULL), 
    mLine(3),
    mRow(-1), 
    mShape(ONE) {
    int red = rand() % 256;
    int green = rand() % 256;
    int blue = rand() % 256;
    mColor = RGB(red, green, blue);
}

/**
 * 析构方法。
 */
Block::~Block() {
}

/**
 * 绘制自身。
 */
void Block::Draw() {
    for (int i = 0; i < Const::BLOCK_GRID_COUNT_H; i++) {
        for (int j = 0; j < Const::BLOCK_GRID_COUNT_V; j++) {
            if (!mBlocks[i][j].mUsed) {
                continue;
            }

            int left = Const::GRID_SIZE * (mLine + j);
            int top = Const::GRID_SIZE * (mRow + i);
            CRect rect(left, top, left + Const::GRID_SIZE, top + Const::GRID_SIZE);
            mDrawer->FillSolidRect(rect, mColor);
            mDrawer->DrawEdge(rect, EDGE_RAISED, BF_RECT);
        }
    }

    mGameBoard->Invalidate(FALSE);
}

/**
 * 进入游戏区域。
 * @param gameBoard 游戏区域
 * @param drawer    绘图者
 */
void Block::EnterGameboard(CWnd* gameBoard, CDC* drawer) {
    mGameBoard = gameBoard;
    mDrawer = drawer;
    this->Draw();
}

/**
 * 进入预览区域。
 * @param drawer    绘图者
 */
void Block::EnterPreview(CDC* drawer) {
    int x = (Const::PREVIEW_WIDTH - Const::GRID_SIZE * 3) / 2;
    int y = Const::PREVIEW_HEIGHT / 2 - Const::GRID_SIZE * 2;

    // 遍历所有格，跳过无效的，画有效的
    for (int i = 0; i < Const::BLOCK_GRID_COUNT_H; i++) {
        for (int j = 0; j < Const::BLOCK_GRID_COUNT_V; j++) {
            if (!mBlocks[i][j].mUsed) {
                continue;
            }

            CRect rect(x + Const::GRID_SIZE * j, y + Const::GRID_SIZE * i,
                x + Const::GRID_SIZE * (j + 1), y + Const::GRID_SIZE * (i + 1));
            drawer->FillSolidRect(rect, mColor);
            drawer->DrawEdge(rect, EDGE_RAISED, BF_RECT);
        }
    }
}

/**
 * 擦除矩形。
 * @param block 方块
 * @param rect  矩形
 */
void Block::EraseRect(RECT* rect) {
    mDrawer->FillSolidRect(rect, Const::GAME_BOARD_COLOR);
}

/**
 * 下落。
 * @return 总是 TRUE
 */
BOOL Block::MoveDown() {
    this->Erase();
    mRow++;
    this->Draw();

    return TRUE;
}

/**
 * 左移。
 */
void Block::MoveLeft() {
    this->Erase();
    mLine--;
    this->Draw();
}

/**
 * 右移。
 */
void Block::MoveRight() {
    this->Erase();
    mLine++;
    this->Draw();
}
